﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using EPiServer.Web;
using EPiServer.Core;

namespace EPiServer
{
    public class PageDataModelBinder : IModelBinder
    {
        #region IModelBinder Members

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string pagePath = (string)controllerContext.RouteData.Values["pagePath"];
            return GetPageFromUrl(pagePath);
        }

        #endregion


        //ted nyberg
        private PageData GetPageFromUrl(string rawUrl)
        {
            if (rawUrl.Contains("_"))
            {
                PageReference pr;
                var urlString = rawUrl;
                if (urlString.EndsWith("/"))
                    urlString = urlString.Substring(0, urlString.Length - 1);

                if (PageReference.TryParse(urlString, out pr))
                {
                    return DataFactory.Instance.GetPage(pr);
                }
            }


            rawUrl = rawUrl.Replace("_", "/");

            if (!rawUrl.StartsWith("/"))
                rawUrl = "/" + rawUrl;

            ProviderSettings settings = new ProviderSettings("EPiServerFriendlyUrlRewriteProvider", "EPiServer.Web.FriendlyUrlRewriteProvider");
            UrlRewriteProvider provider = FriendlyUrlRewriteProvider.CreateInstance(settings);
            UrlBuilder url = new UrlBuilder(VirtualPathUtility.AppendTrailingSlash(rawUrl));
            
            if(rawUrl == "/")
                return DataFactory.Instance.GetPage(PageReference.StartPage);

            object rewrittenUrl;

            if (provider.ConvertToInternal(url, out rewrittenUrl))
            {
                if (rewrittenUrl != null && rewrittenUrl is PageReference)
                {
                    PageReference link = (PageReference)rewrittenUrl;

                    return DataFactory.Instance.GetPage(link);
                }
            }

            return null;
        }
    }
}